package com.ruicar.afs.cloud.afscase.infomanagement.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseRedundantInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseProductService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseRedundantInfoService;
import com.ruicar.afs.cloud.bizcommon.business.bean.FinanceCalculatorBean;
import com.ruicar.afs.cloud.bizcommon.business.bean.FinanceInfoBean;
import com.ruicar.afs.cloud.bizcommon.business.dto.CalculatorDTO;
import com.ruicar.afs.cloud.bizcommon.business.dto.CalculatorListDTO;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinDiscountDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinRentAdjustDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyRentAdjustDetailsService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.CostTypeEnum;
import com.ruicar.afs.cloud.parameter.commom.enums.CostType;
import com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 金融产品
 * @author: sijun.yu
 * @date: 2020/8/4 19:25
 */
@Slf4j
@RestController
@RequestMapping(value = "product")
@AllArgsConstructor
public class CaseProductController {

    private CaseProductService caseProductService;
    private ApplyCostDetailsService costDetailsService;
    private ApplyRentAdjustDetailsService rentAdjustDetailsService;
    private CaseBaseInfoService caseBaseInfoService;
    private CaseRedundantInfoService redundantInfoService;

    /**
     * 查看产品详情
     * @param condition
     * @return
     */
    @ApiOperation("查看产品详情")
    @PostMapping(value = "/queryProductDetails")
    public IResponse queryProductDetails(@ModelAttribute CalculatorDTO condition){

        return caseProductService.queryProductDetails(condition);
    }

    /**
     * 获取产品利率
     * @param condition
     * @return
     */
    @ApiOperation("获取产品利率")
    @PostMapping(value = "/getProductRate")
    public IResponse getProductRate(@ModelAttribute CalculatorDTO condition){

        return caseProductService.getProductRate(condition);
    }

    /**
     * 查询贷款信息【汇总】
     * @param condition
     * @return
     */
    @PostMapping(value = "/getFinanceCostAll")
    @ApiOperation("查询贷款信息【汇总】")
    public IResponse getFinanceCostAll(@ModelAttribute CalculatorDTO condition){
        //add by gjq 附条件核准留痕
        CaseRedundantInfo redundantInfo= redundantInfoService.getOne(Wrappers.<CaseRedundantInfo>query().lambda()
                .eq(StringUtils.isNotBlank(condition.getApplyNo()),CaseRedundantInfo::getApplyNo,condition.getApplyNo()));
        JSONObject jsonObject=null;
        if(ObjectUtils.isNotEmpty(redundantInfo)){
            String conditionalApproval=redundantInfo.getConditionalApproval();
            if(StringUtils.isNotBlank(conditionalApproval)){
                jsonObject= JSONObject.parseObject(conditionalApproval);
            }
        }

        FinanceCalculatorBean vo = new FinanceCalculatorBean();
        String applyNo = condition.getApplyNo();
        // 合计信息
        costDetailsService.getFinanceCostTotal(vo, condition);
        if(ObjectUtils.isNotEmpty(jsonObject)){
            /** add by gjq **/
            this.getFinanceCostTotalOld(vo, jsonObject);
        }
        // 附加产品
        String isAdditional = WhetherEnum.No.getIndex();
        FinanceInfoBean addProductInfo = costDetailsService.getAddProductInfo(applyNo, condition.getCarId(), CostType.AFFIXAMT.getIndex());
        // 车辆产品
        FinanceInfoBean carProductInfo = costDetailsService.getCarProductInfo(applyNo, condition.getCarId(), CostType.CARAMT.getIndex());
        // 是否有子产品
        BigDecimal totalContractAmtOld=vo.getTotalContractAmtOld();
        if (carProductInfo != null) {
            FinCostDetails costInfo = carProductInfo.getCostInfo();
            String isSubProduct = costInfo.getIsSubProduct();
            if (WhetherEnum.No.getIndex().equals(isSubProduct)) {
                isAdditional = WhetherEnum.YES.getIndex();
                vo.setIsAdditional(isAdditional);
            }
            vo.setIsSubProduct(isSubProduct);
            carProductInfo.setCostInfo(costInfo);
            if(ObjectUtils.isNotEmpty(jsonObject)){
                JSONArray costDetailsList=jsonObject.getJSONArray("finCostDetailsList");
                if(ObjectUtils.isNotEmpty(costDetailsList)&&costDetailsList.size()>0){
                    costDetailsList.toJavaList(FinCostDetails.class).forEach(cost ->{
                        if(cost.getCostType().equals(CostTypeEnum.CARAMT.getCode())){
                            FinCostDetails costDetails = new FinCostDetails();
                            BeanUtils.copyProperties(cost, costDetails);
                            carProductInfo.setCostInfoOld(costDetails);
                        }else{
                            FinCostDetails costDetails = new FinCostDetails();
                            BeanUtils.copyProperties(cost, costDetails);
                            addProductInfo.setCostInfoOld(costDetails);
                        }
                    });
                    log.info("融资信息留痕数据查询成功！！！");
                }

                //附加贷
                JSONArray arrayFinancing=jsonObject.getJSONArray("finFinancingItemsList");
                if(ObjectUtils.isNotEmpty(arrayFinancing)&&arrayFinancing.size()>0){
                    ArrayList<FinFinancingItems> financingItemsList = new ArrayList<>();
                    arrayFinancing.toJavaList(FinFinancingItems.class).forEach(fin ->{
                        FinFinancingItems finFinancingItems = new FinFinancingItems();
                        BeanUtils.copyProperties(fin, finFinancingItems);
                        financingItemsList.add(finFinancingItems);
                        if(fin.getSonList()!=null&&fin.getSonList().size()>0){
                            fin.getSonList().forEach(son ->{
                                FinFinancingItems finFinancing = new FinFinancingItems();
                                BeanUtils.copyProperties(son, finFinancing);
                                financingItemsList.add(finFinancing);
                            });
                        }
                    });
                    carProductInfo.setItemListOld(financingItemsList);
                    log.info("融资信息留痕数据查询成功！！！");
                }
            }
            if (addProductInfo != null) {
                /**贴息留痕 附加贷*/
                if(ObjectUtils.isNotEmpty(jsonObject)){
                    addProductInfo.setDiscountListOld( this.getFinDiscountInfo(jsonObject,CostType.AFFIXAMT.getIndex()));
                    log.info("贴息留痕数据查询成功！！！");
                }
                isAdditional = WhetherEnum.YES.getIndex();
                vo.setIsAdditional(isAdditional);
                vo.setAddProductInfo(addProductInfo);

            }
            vo.setTotalContractAmtOld(totalContractAmtOld);
            /**贴息留痕 车贷*/
            if(ObjectUtils.isNotEmpty(jsonObject)){
                carProductInfo.setDiscountListOld( this.getFinDiscountInfo(jsonObject,CostType.CARAMT.getIndex()));
                log.info("贴息留痕数据查询成功！！！");
            }


            vo.setCarProductInfo(carProductInfo);
        }
        // 租金调整
        List<FinRentAdjustDetails> rentList = rentAdjustDetailsService.getRentAdjustDetails(condition.getApplyNo());
        if (rentList != null && rentList.size() > 0) {
            vo.setRentList(rentList);
        }
        return IResponse.success(vo);
    }

    /**
     * 更新融资信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/updateCostList")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("更新融资列表")
    public IResponse updateCostList(@RequestBody CalculatorListDTO condition) {

        List<FinCostDetails> resultList = caseProductService.updateCostList(condition.getApplyNo(),condition.getCostList());
        return IResponse.success(resultList);
    }

    /**
     * 调用计算器生成多个还款计划表
     * @param condition
     * @return
     */
    @ApiOperation("调用计算器")
    @PostMapping("/financeCalculation")
    public IResponse financeCalculation(@RequestBody CalculatorListDTO condition) {

        return caseProductService.financeCalculation(condition.getCostList());
    }

    /**
     * 金融产品-融资计算器
     * @param condition
     * @return
     */
    @ApiOperation("金融产品-融资计算器")
    @PostMapping("/financeProductCalculation")
    public IResponse financeProductCalculation(@RequestBody CalculatorListDTO condition){

        return caseProductService.financeProductCalculation(condition);
    }
    /**
     * @description: 贴息明细查询
     * @author jiaqi.guo
     * @created 2020/8/14 18:45
     * @version 1.0
     */
    public List<FinDiscountDetails> getFinDiscountInfo(JSONObject jsonObject,String costType){
        JSONArray discountList=jsonObject.getJSONArray("finDiscountDetailsList");
        if(ObjectUtils.isNotEmpty(discountList)&&discountList.size()>0){
            ArrayList<FinDiscountDetails> finDiscountDetailsList = new ArrayList<>();
            for (FinDiscountDetails discountDetails : discountList.toJavaList(FinDiscountDetails.class)) {
                if(discountDetails.getCostType().equals(costType)){
                    FinDiscountDetails details = new FinDiscountDetails();
                    BeanUtils.copyProperties(discountDetails, details);
                    finDiscountDetailsList.add(details);
                }
            }
            return  finDiscountDetailsList;
        }
        return  null;
    }

    /**
     * @description: 获取融资信息合计信息
     * @author jiaqi.guo
     * @created 2020/8/14 19:07
     * @version 1.0
     */
    public void getFinanceCostTotalOld(FinanceCalculatorBean vo,JSONObject jsonObject) {
        //融资信息
        JSONArray  costDetailsList=jsonObject.getJSONArray("finCostDetailsList");
        ArrayList<FinCostDetails> finCostDetailsList = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(costDetailsList)&&costDetailsList.size()>0){
            for (FinCostDetails finCostDetails : costDetailsList.toJavaList(FinCostDetails.class)) {
                FinCostDetails costDetails = new FinCostDetails();
                BeanUtils.copyProperties(finCostDetails, costDetails);
                finCostDetailsList.add(costDetails);
            }
            log.info("或去除资产变更融资信息成功！！！");
        }
        if (costDetailsList == null || costDetailsList.size() == 0) {
            return;
        }
        // 汇总金额
        BigDecimal totalContractAmt = BigDecimal.ZERO;
        BigDecimal totalLoanAmt = BigDecimal.ZERO;
        BigDecimal totalFirstAmt = BigDecimal.ZERO;
        BigDecimal totalDiscountAmt = BigDecimal.ZERO;
        BigDecimal totalInterest = BigDecimal.ZERO;
        BigDecimal totalRent = BigDecimal.ZERO;
        BigDecimal totalTailAmt = BigDecimal.ZERO;
        for (FinCostDetails costDetails : finCostDetailsList) {
            totalContractAmt = totalContractAmt.add(costDetails.getContractAmt() == null ? BigDecimal.ZERO : costDetails.getContractAmt());
            totalLoanAmt = totalLoanAmt.add(costDetails.getLoanAmt() == null ? BigDecimal.ZERO : costDetails.getLoanAmt());
            totalFirstAmt = totalFirstAmt.add(costDetails.getDownPayAmt() == null ? BigDecimal.ZERO : costDetails.getDownPayAmt());
            totalDiscountAmt = totalDiscountAmt.add(costDetails.getDiscountAmt() == null ? BigDecimal.ZERO : costDetails.getDiscountAmt());
            totalRent = totalRent.add(costDetails.getTotalRent() == null ? BigDecimal.ZERO : costDetails.getTotalRent());
            totalInterest = totalInterest.add(costDetails.getTotalInterest() == null ? BigDecimal.ZERO : costDetails.getTotalInterest());
            totalTailAmt = totalTailAmt.add(costDetails.getTailPayAmt() == null ? BigDecimal.ZERO : costDetails.getTailPayAmt());
        }
        vo.setTotalContractAmtOld(totalContractAmt);
        vo.setTotalLoanAmtOld(totalLoanAmt);
        vo.setTotalFirstAmtOld(totalFirstAmt);
        vo.setTotalDiscountAmtOld(totalDiscountAmt);
        vo.setTotalInterestOld(totalInterest);
        vo.setTotalRentOld(totalRent);
        vo.setTotalTailAmtOld(totalTailAmt);
    }
}
